import asyncio
from pprint import pprint
from typing import Dict, Any, Optional, List
import datetime
from bilibili_api.user import User, VideoOrder
from app.core.config import POSTER_INFO
from app.schema.common import VideoInfo, ReportBaseInfo



async def fetch_latest_with_keyword(uid: int, keyword: str) -> Optional[VideoInfo]:
    user = User(uid=uid)
    resp = await user.get_videos(ps=50, pn=1, order=VideoOrder.PUBDATE, keyword=keyword)
    try:
        vlist: List[Dict[str, Any]] = resp["list"]["vlist"]
    except Exception:
        return None
    if not vlist:
        return None
    v = vlist[0]
    
    return VideoInfo(
        title=v.get("title", ""),
        bvid=v.get("bvid", ""),
        description=v.get("description", ""),
        length=v.get("length", ""),
        created=datetime.datetime.fromtimestamp(int(v.get("created", 0))).strftime("%Y-%m-%d")
    )


async def main():
    report_items: List[str] = []
    tasks = []
    for item_name, info in POSTER_INFO.items():
        uid = info.get("uid")
        keyword = info.get("keyword", "")
        if not uid:
            continue
        report_items.append(item_name)
        tasks.append(fetch_latest_with_keyword(uid, keyword))

    results = await asyncio.gather(*tasks, return_exceptions=True)
    output: List[ReportBaseInfo] = []
    for item_name, res in zip(report_items, results):
        if isinstance(res, Exception) or res is None:
            continue
        report_info = ReportBaseInfo(
            report_name=item_name,
            video_info=res
        )
        output.append(report_info)
    
    for item in output:
        pprint(item)


if __name__ == "__main__":
    asyncio.run(main())